// content.js
var util = require('../../utils/util.js')
var glo = require('../../utils/global.js')
var sectionList = [];
var verseList = [];
var contentArrX = new Array();
var leftChapter = {};
var rightChapter = {};
var currChapter = {};
//var longtab = false;
var selVerseClass = "background-color: #e8cc6b;"
var cancleClass = "font-size: 9pt;"
var locationId = -1;
var pageFrom = -1;
var line_image = "line" //"../../images/edit/line.png";
var del_image = "del" //"../../images/edit/del.png";
var sign_def = "display:none";
var app = getApp();
var bibleData = require('../../utils/bible.js')
var oldbook = "";
var newbook = "";
var oldTimeStamp = 0;
var lastLen=15;
const backgroundAudioManager = wx.getBackgroundAudioManager();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currPage: 0,
    currTabNum: 0,
    bookId: 0,
    bookName: "",
    chapterId: 0,
    chapterCount: 0,
    userInfo: [],
    subtitles: [],
    lastX: 0,
    lastY: 0,
    currentGesture: 0,
    status: true,
    veridpre: "",
    contentArr: [],
    cancle_class: "",
    bottom_menu: "bottom_menu_none",
    ismark: line_image,
    sign: sign_def,
    hasSign: false,
    /*以下是弹出菜单 */
    isPopping: true, //是否已经弹出  
    animPlus: {}, //旋转动画  
    animCollect: {}, //item位移,透明度  
    animTranspond: {}, //item位移,透明度  
    animInput: {}, //item位移,透明度 
    /*音频播放全局*/
    audioState: false,
    homeimage: 'home',
    punchimage: 'punch',
    sliderV: 'none',
    menuV: 'none',
    bkcolor: '#edf4fd',
    fontcolor: '#1B1919',
    bright: 'moon',
    isNight: false,
    isToggle: false,
    isViewhistory:false,
    isCheck: true,
    isOpenDaka: false,
    isOpenSet: false,
    setpagebgnum: 4, //默认设置
    pagetext: 'default', //默认段落，可选择书写
    fontsize: 38, //38rpx;
    bottomDakaShow: false,
    speed: 1, //速度默认正常
    swichNext: true, //自动跳转下一章
    tapVerse: 0,
    selVerArr: [],
    selVerseValue: 1,
    scrollTool: false, //滚动隐藏工具栏
    selVesCount: 0,
    bkey:decodeURI("%E5%9C%A3%E7%BB%8F"),
    zn: decodeURI("%E4%B8%BB%E5%86%85") ,
    tit: '3:20,21,27,31,37,38,39',
    text: '通过社交',
    imgSrc: '../../images/blank.png', //glo.https+ '/static/images/poster.png'//
    lineSrc: '../../images/oblique_line.png',
    cardvisible: 'none',
    dakaNext: false, //是否跳转
    isPop: false,
    shortChapter: false,
    todaycount: 0,
    locationId: 0,
    bottomDakaShow2: false,
    posterIndex: 0,
    cardH: 962,
    notbetext: decodeURI("%E7%AC%94%E8%AE%B0"),
    cardtips: decodeURI("%E4%BF%9D%E5%AD%98%E5%88%B0%E7%9B%B8%E5%86%8C%E5%90%8E%EF%BC%8C%E5%8F%AF%E5%88%B0%E6%9C%8B%E5%8F%8B%E5%9C%88%E5%88%86%E4%BA%AB%E8%AF%A5%E5%8D%A1%E7%89%87"),
    bckp: decodeURI("%E4%BF%9D%E5%AD%98%E5%8D%A1%E7%89%87"),
    gxzfxts: decodeURI("%E7%82%B9%E5%87%BB%E2%80%98%E6%84%9F%E8%B0%A2%E4%B8%BB%E2%80%99%E5%AF%B9%E8%AF%9D%E6%A1%86%E5%8F%91%E9%80%81%E2%80%987%E2%80%99%E8%8E%B7%E5%8F%96%E8%AF%BB%E7%BB%8F%E6%89%93%E5%8D%A1%E6%88%90%E7%BB%A9%E9%93%BE%E6%8E%A5%E5%88%86%E4%BA%AB%E6%9C%8B%E5%8F%8B%E5%9C%88%E3%80%82"),
    jw: decodeURI("%E7%BB%8F%E6%96%87"),
    dk: decodeURI("%E6%89%93%E5%8D%A1"),
    gxz: decodeURI("%E6%84%9F%E8%B0%A2%E4%B8%BB"),
    fx: decodeURI("%E5%88%86%E4%BA%AB"),
    fxpyq: decodeURI("%E5%8F%AF%E4%BB%A5%E5%88%86%E4%BA%AB%E6%88%90%E7%BB%A9%E5%88%B0%E6%9C%8B%E5%8F%8B%E5%9C%88")
  },
  viewHistory:function(){
        var that=this;
        var bool = that.data.isViewhistory;
        that.setData({ isViewhistory: !bool});
        //that.toggleDown(null);
  },
  tapshare: function() { //改
    var that = this;
    //console.log(JSON.stringify(that.data.userInfo));
    //return;
    var myDate = new Date();
    var date = new Date;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" + month : month);
    var day = myDate.getDate();
    var mydate = (year.toString() + '-' + month.toString() + '-' + day);
    console.log(mydate);

    wx.request({
      url: glo.https + '/share/recordData',
      data: {
        openid: that.data.userInfo.wxId,
        userid: that.data.userInfo.userId,
        date: mydate
      },
      method: 'GET',
      success: function(res) {
        // if (that.data.punchimage == 'read') {
        //   return;
        // }
        that.setData({
          isPop: true
        });
        var punch = that.data.userInfo.punch;
        var target = that.data.userInfo.target;
        var bookId = parseInt(currChapter.bookId);
        var chapterId = parseInt(currChapter.chapterId);
        var chapterCount = parseInt(currChapter.chapterCount);
        var bookName = currChapter.bookName;
        var date = util.getNowShortFormatDate();
        var punch1 = date + "-" + bookId + "-" + chapterId;
        punch = punch + ";" + "#" + date + "-" + bookId + "-" + chapterId + "#";

        var result = glo.punchCalc1(punch);
        var todaycount = result.todaycount;
        var todayval = result.todayval;
        var remcount = target - todaycount;

        var bibleRead = wx.getStorageSync('bibleRead');
       
      }
    });


  },
  share_qx: function() { //改
    this.setData({
      isPop: false
    });
  },
  tolower: function(e) { //触碰到底部 
    var that = this;
    if (this.data.isOpenDaka) {
      if (that.data.punchimage == 'read' && that.data.audioState === false) {
        wx.showToast({
          title: '已' + decodeURI('%E6%89%93%E5%8D%A1')+'的章节',
          duration: 2000
        })
        return;
      }
      if (that.data.audioState === true) {
        return;
      } else {
        setTimeout(function() {
          that.setData({
            bottomDakaShow: true
          });
        }, 200);
      }
    }
  },
  cancelSet: function() {
    var that = this;
    var obj = {
      pagetext: 'default', //默认段落，可选择书写
      fontsize: 38, //38rpx;
      bottomDakaShow: false,
      speed: 1, //速度默认正常
      swichNext: true,
      isNight: false
    }
    var bgObj = {
      bkcolor: '#edf4fd',
      fontcolor: '#1B1919',
      setpagebgnum: 4, //默认设置
    }

    wx.showModal({
      title: '提示',
      content: '确定恢复初始设置？',
      success: function(res) {
        if (res.confirm) {
          //网络请求
          that.setData(obj);
          that.setData(bgObj);
          for (var i in obj) {
            wx.setStorage({
              key: i,
              data: obj[i]
            });
          }
          wx.setStorage({
            key: 'bg',
            data: bgObj,
          });
        } else {}
      }
    });

  },
  switch1Change: function(e) {
    var val = e.detail.value;
    this.setData({
      swichNext: val
    });
    wx.setStorage({
      key: 'swichNext',
      data: val
    });
  },
  changeSpeed: function(e) {
    var key = e.target.dataset.key;
    var that = this;
    if (key == this.data.speed) {
      return;
    }
    this.setData({
      speed: key
    });
    wx.setStorage({
      key: 'speed',
      data: key
    });


  },
  setpagebg: function(e) {
    console.log(e);
    var that = this;
    var data = e.target.dataset;
    var bkcolor = data.color;
    var fontcolor = '#1B1919';
    var setpagebgnum = data.num;
    var bgObj = {};
    if (setpagebgnum == 5) {
      fontcolor = '#fff';
      that.setData({
        isNight: true
      });
    } else {
      that.setData({
        isNight: false
      });
    }

    bgObj = {
      bkcolor: bkcolor,
      fontcolor: fontcolor,
      setpagebgnum: setpagebgnum
    }
    this.setData(bgObj);

    wx.setStorage({
      key: 'bg',
      data: bgObj,
    });
  },
  fontSizeChang: function(e) {
    var bool = e.target.dataset.sub;
    var size = this.data.fontsize;
    if (bool == '-') {
      size -= 1;
    } else {
      size += 1
    }
    if (size === 31 || size === 71) {
      return;
    }
    this.setData({
      fontsize: size
    });
    wx.setStorage({
      key: "fontsize",
      data: size
    });
  },
  setTextSize: function(e) {
    var fontsize = e.detail.value;
    this.setData({
      fontsize: fontsize
    });
    wx.setStorage({
      key: "fontsize",
      data: fontsize
    });
  },
  setSpeed: function(e) {
    var sp = e.detail.value;
    var that = this;
    sp = (sp.toFixed(1)) * 1;
    this.setData({
      speed: sp
    });
    wx.setStorage({
      key: "speed",
      data: sp
    });

    //改变速度时 是否已经选择
    if (that.data.audioState && !backgroundAudioManager.paused) {
      if (that.data.tapVerse !== 0) {
        backgroundAudioManager.stop();
        that.playBibleAudio.url = '';
        let v = that.data.selVerseValue;
        if (v !== 0) {
          that.audioplay(v);
        } else {
          that.audioplay(1);
        }
      } else {
        backgroundAudioManager.stop();
        that.playBibleAudio.url = '';
        that.audioplay(1);
      }
    }
  },
  speedChange: function(e) {
    var bool = e.target.dataset.sub;
    var that = this;
    var val = this.data.speed * 1;

    if (bool == '-') {
      val -= 0.1;
    } else {
      val += 0.1
    }
    if (val === 0.6 || val === 2.6) {
      return;
    }
    val = (val.toFixed(1)) * 1;

    this.setData({
      speed: val
    });
    wx.setStorage({
      key: "speed",
      data: val
    });

    //改变速度时 是否已经选择
    if (that.data.audioState && !backgroundAudioManager.paused) {
      if (that.data.tapVerse !== 0) {
        backgroundAudioManager.stop();
        that.playBibleAudio.url = '';
        let v = that.data.selVerseValue;
        if (v !== 0) {
          that.audioplay(v);
        } else {
          that.audioplay(1);
        }
      } else {
        backgroundAudioManager.stop();
        that.playBibleAudio.url = '';
        that.audioplay(1);
      }
    }
  },
  changeParagraph: function(e) {
    var data = e.target.dataset;
    this.setData({
      pagetext: data.text
    });
    wx.setStorage({
      key: "pagetext",
      data: data.text
    });
  },
  openSet: function() {
    var bool = !this.data.isOpenSet;
    this.setData({
      isOpenSet: bool
    });
  },
  backUrl: function(e) {
    var url = e.target.dataset.url;
    if (url == '../index/index') {
      wx.switchTab({
        url: url,
      });
      return;
    }

    wx.navigateTo({
      url: url,
      success: function(res) {
        console.log("返回成功");
      },
      fail: function(res) {
        console.log("返回失败");
      },
      complete: function(res) {},
    })
  },
  toggleDown: function(e) { //切换
    var bool = this.data.isToggle;
    this.setData({
      isToggle: !bool
    })
     if(!bool){
       this.setData({
         isViewhistory: false
       })
     }
  
  },
  toggleCheckbox: function() {
    this.setData({
      isCheck: !this.data.isCheck
    })
  },
  nextContent: function() {
    var that = this;
    if (that.data.punchimage == 'read') {
      var currTabNum = that.data.currTabNum;
      currTabNum++;
      if (currTabNum == 3) {
        currTabNum = 0;
      }
      that.setData({
        currTabNum: currTabNum,
        dakaNext: true
      });
      return;
    }
    var userInfo = that.data.userInfo;
    var punch = userInfo.punch;
    var target = userInfo.target;
    var bookId = parseInt(currChapter.bookId);
    var chapterId = parseInt(currChapter.chapterId);
    var chapterCount = parseInt(currChapter.chapterCount);
    var bookName = currChapter.bookName;
    var date = util.getNowShortFormatDate();
    var punch1 = date + "-" + bookId + "-" + chapterId;
    console.log(punch)
    punch = punch + ";" + "#" + date + "-" + bookId + "-" + chapterId + "#";

    var result = glo.punchCalc1(punch);
    var todaycount = result.todaycount;
    var todayval = result.todayval;
    var remcount = target - todaycount;
    var punchMsg = "目标达成。"
    if (remcount > 0) {
      punchMsg = "加油继续..."; // + remcount + "章";
    }
    if (remcount < 0) {
      punchMsg = "太棒了!!!"; // + todaycount + "章";
    }
    var bibleRead = wx.getStorageSync('bibleRead');
    console.log(punch1)
    wx.request({
      url: glo.https + '/person/punch_update1',
      data: {
        punch: punch1,
        userid: userInfo.userId,
        punchcount: todaycount,
        target: target,
        punchdate: date,
        todaycount: todaycount,
        punchval: todayval
      },
      success: function(res2) {
        console.log(res2);
        console.log(punch);
        bibleRead[bookId - 1][chapterId] = bibleRead[bookId - 1][chapterId] + 1;
        wx.setStorageSync('bibleRead', bibleRead);
        userInfo.punch = punch;
        //app.setUserInfo(that.data.userInfo);
        that.setData({
          sign: sign_def,
          hasSign: true,
          userInfo: userInfo,
          todaycount: todaycount
        });
        that.setData({
          bottomDakaShow: false,
          punchimage: 'read', 
          isPop: false
        });
        wx.showToast({
          title: punchMsg,
          duration: 1000
        });
        var lastread = bookId + "-" + chapterId + "-" + bookName + "-" + chapterCount + "-" + "1"; 
        wx.request({
          url: glo.https + '/person/lastread_update',
          data: {
            lastread: lastread,
            userid: userInfo.userId,
          },
          success: function(res2) {
            userInfo.lastRead = lastread;
            app.setUserInfo(userInfo);
            that.setData({
              userInfo: userInfo
            });
            //最近读到
            if (chapterId < chapterCount) {
              chapterId = chapterId + 1;
            } else {
              chapterId = 1;
              if (bookId < 66) {
                bookId = bookId + 1;
              } else {
                bookId = 1;
              }
              if (bookId > 39) {
                bookName = newbook[bookId - 40].bookName;
                chapterCount = newbook[bookId - 40].chapterCount;
              } else {
                bookName = oldbook[bookId - 1].bookName
                chapterCount = newbook[bookId - 1].chapterCount;
              }
            }
            lastread = bookId + "-" + chapterId + "-" + bookName + "-" + chapterCount + "-" + "1";
            wx.setStorageSync("lastread", lastread);
            var date = util.getNowShortFormatDate();
            var lastreadid = date + "-" + bookId + "-" + chapterId;
            glo.setLastRead(lastreadid);
            //that.setData({ punchimage: 'read' });
            //切到下一章

            if (that.data.swichNext) {
              var currTabNum = that.data.currTabNum;
              currTabNum++;
              if (currTabNum == 3) {
                currTabNum = 0;
              }
              that.setData({
                currTabNum: currTabNum,
                dakaNext: true
              });
            } else {
              //隐藏 
            }
          },
          fail: function(res2) {}
        })
      },
      fail: function(res2) {
        console.log('失败:' + res2.errMsg);
        wx.showToast({
          title: decodeURI('%E6%89%93%E5%8D%A1')+'失败，检查网络',
          icon: 'loading',
          duration: 2000
        })
      }
    })


  },
  //点击弹出  
  plus: function() {

    if (this.data.audioState) {
      this.setData({
        homeimage: 'home',
        audioState: false
      });
      backgroundAudioManager.stop();
      return;
    }
    if (this.data.isPopping) {
      //弹出动画  
      this.popp();
      this.setData({
        isPopping: false
      })
    } else if (!this.data.isPopping) {
      //缩回动画  
      this.takeback();
      this.setData({
        isPopping: true
      })
    }
  },
  //弹出动画  
  popp: function() {
    if (this.data.menuV == 'none') {
      this.setData({
        menuV: 'display'
      });
    }

    //plus顺时针旋转  
    var animationPlus = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationcollect = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationTranspond = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationInput = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    animationPlus.rotateZ(45).step();
    animationcollect.translate(-100, -100).rotateZ(360).opacity(1).step();
    animationTranspond.translate(-140, 0).rotateZ(360).opacity(1).step();
    animationInput.translate(-100, 100).rotateZ(3600).opacity(1).step();
    this.setData({
      animPlus: animationPlus.export(),
      animCollect: animationcollect.export(),
      animTranspond: animationTranspond.export(),
      animInput: animationInput.export(),
    })
  },
  //收回动画  
  takeback: function() { //plus逆时针旋转  

    var animationPlus = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationcollect = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationTranspond = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationInput = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    animationPlus.rotateZ(0).step();
    animationcollect.translate(0, 0).rotateZ(0).opacity(0).step();
    animationTranspond.translate(0, 0).rotateZ(0).opacity(0).step();
    animationInput.translate(0, 0).rotateZ(0).opacity(0).step();
    this.setData({
      animPlus: animationPlus.export(),
      animCollect: animationcollect.export(),
      animTranspond: animationTranspond.export(),
      animInput: animationInput.export(),
    })
  },
  //根据节数调节scrollview高度
  setChapter: function(bookId, chapterId) {
    let that = this;
    wx.request({
      url: glo.https + '/verse/chapter',
      data: {
        bookid: bookId,
        chapterid: chapterId,
      },
      success: function(res) {
        let sys = wx.getSystemInfoSync(),
          len = res.data.length;
        if (len < 9) {
          that.setData({
            shortChapter: true
          })
        } else {
          that.setData({
            shortChapter: false
          })
        }
      }
    });
  },

  refuContentArrX: function(e) {
    var that = this;
    var currPage = that.data.currPage;
    var favorite = that.data.userInfo.favorite;
    currChapter.format = that.transContentArr(currChapter.bookId, currChapter.chapterId, currChapter.content, favorite);
    contentArrX = currChapter.format;
    // if (e && e.detail.source === 'touch') {
    //   that.setChapter(currChapter.bookId, currChapter.chapterId);
    // }
    if (currPage == 0) {
      that.setData({
        contentArr0: currChapter.format
      });
    } else if (currPage == 1) {
      that.setData({
        contentArr1: currChapter.format
      });
    } else {
      that.setData({
        contentArr2: currChapter.format
      });
    }
  },
  tap_card: function(e) {
    var that = this;
    var copydata = "";
    var selContents = new Array();
    var selIndexs = new Array();
    var selChapters = new Array();
    var currPage = that.data.currPage;
    this.getSelVers(selContents, selIndexs, selChapters);
    var text = "";
    var tit = "";
    for (var i = 0; i < selContents.length; i++) {
      text = text + selContents[i];
      if (i == 0) {
        tit = tit + selIndexs[i];
      } else {
        var arr0 = selIndexs[i].split(':');
        tit = tit + ";" + arr0[1];
      }
      //copydata = copydata + selContents[i] + "(" + selIndexs[i] + ")";
    }


    var n = Math.ceil(text.length / 19);
    var n0 = 0;
    var cardHx = 962;
    //var n1=n;
    if (n > 5) {
      n0 = n - 5;
      cardHx = 962 + n0 * 42;
    }

    that.setData({
      cardvisible: '',
      text: text,
      tit: tit,
      cardH: cardHx
    });
    that.tapcancel();
    // wx.navigateTo({
    //   url: '../card/card?text=' + text + '&tit=' + tit,
    // })
  },

  bright_tap: function(e) {
    var that = this;
    that.plus();
    if (!that.data.isNight) {
      that.setData({
        bkcolor: 'black',
        fontcolor: 'white',
        bright: 'sun',
        isNight: true
      });
    } else {
      that.setData({
        bkcolor: '#f8f8f8',
        fontcolor: 'black',
        bright: 'moon',
        isNight: false
      });
    }
    that.refuContentArrX();
  },

  
  transContentArr: function(bookId, chapterId, content, favorite) {
    favorite = favorite || '';
    var that = this;
    sectionList = content.split("%");
    var contentArrX = new Array();
    for (var i = 0; i < sectionList.length; i++) {
      contentArrX[i] = new Array();
      if (sectionList[i] == "") { //"22222" 表示一个空格行
        contentArrX[i][0] = "22222";
      } else if (sectionList[i].indexOf("||") == -1) {
        contentArrX[i][0] = "00000"; //"00000" 表示一个段标题
        contentArrX[i][1] = sectionList[i];
        contentArrX[i][2] = "11111";
        if (sectionList[i].indexOf("(") > -1) {
          var titles = sectionList[i].split("(");
          contentArrX[i][1] = titles[0];
          contentArrX[i][2] = "(" + titles[1];
        }
      } else {
        verseList = sectionList[i].split("$");
        if (verseList[0] == "") {
          verseList.splice(0, 1);
        }
        for (var j = 0; j < verseList.length; j++) {
          contentArrX[i][j] = new Array();
          contentArrX[i][j][0] = verseList[j].split("||")[0];
          contentArrX[i][j][1] = verseList[j].split("||")[1];
          contentArrX[i][j][2] = "";
          contentArrX[i][j][5] = "";
          var vid = ";#" + bookId + "-" + chapterId + "-" + contentArrX[i][j][0] + "#";
          contentArrX[i][j][3] = "";
          contentArrX[i][j][4] = contentArrX[i][j][1].split("#");
          contentArrX[i][j][5] = ""
          var c0 = contentArrX[i][j][1];
          var c1 = c0.replace(/#/g, "");
          contentArrX[i][j][1] = c1;
          if (favorite.indexOf(vid) > -1) {
            if (!that.data.isNight) {
              contentArrX[i][j][3] = "markVerse";
            } else {
              contentArrX[i][j][3] = "markVerse1";
            }
          }
          contentArrX[i][j][6] = bookId + "-" + chapterId + "-" + contentArrX[i][j][0];

        }
      }

    }
    return contentArrX;
  },

  swiperChange: function(event) {
    var that = this;
    var newCurr = event.detail.current;
    var dakaNext = this.data.dakaNext;

    if (that.data.currPage == newCurr) {
      return;
    }
    if (event.detail.source !== 'touch' && dakaNext === false) {
      return;
    }

    this.tapcancel();
    this.setData({
      bottomDakaShow: false,
      scrollTop2: 'top001',
      scrollTop1: 'top001',
      scrollTop0: 'top001',
      currTabNum: newCurr,
      dakaNext: false,
      locationId: 0,
    });

    var favorite = this.data.userInfo.favorite;
    var currPage = that.data.currPage;
    if ((currPage == 0 && newCurr == 1) || (currPage == 1 && newCurr == 2) || (currPage == 2 && newCurr == 0)) { //左滑动
      leftChapter = currChapter;
      currChapter = rightChapter;
      rightChapter = glo.getRightChapter(currChapter.bookId, currChapter.chapterId, currChapter.chapterCount);
      var contentArrRight = that.transContentArr(rightChapter.bookId, rightChapter.chapterId, rightChapter.content, favorite);
      rightChapter.format = contentArrRight;

      if (newCurr == 1) {
        that.setData({
          contentArr2: contentArrRight
        });
      } else if (newCurr == 0) {
        that.setData({
          contentArr1: contentArrRight
        });
      } else {
        that.setData({
          contentArr0: contentArrRight
        });
      }

    } else {
      rightChapter = currChapter;
      currChapter = leftChapter;
      leftChapter = glo.getLeftChapter(currChapter.bookId, currChapter.chapterId, currChapter.chapterCount);
      var contentArrLeft = that.transContentArr(leftChapter.bookId, leftChapter.chapterId, leftChapter.content, favorite);
      rightChapter.format = contentArrLeft;

      if (newCurr == 2) {
        that.setData({
          contentArr1: contentArrLeft
        });
      } else if (newCurr == 1) {
        that.setData({
          contentArr0: contentArrLeft
        });
      } else {
        that.setData({
          contentArr2: contentArrLeft
        });
      }
    }
    that.onPunch();
    that.setData({
      currPage: newCurr
    });
    var title = currChapter.bookName;
    if (title === decodeURI("%E5%B8%96%E6%92%92%E7%BD%97%E5%B0%BC%E8%BF%A6%E5%89%8D%E4%B9%A6")) {
      title = decodeURI("%E5%B8%96%E5%89%8D")
    }
    if (title === decodeURI("%E5%B8%96%E6%92%92%E7%BD%97%E5%B0%BC%E8%BF%A6%E5%90%8E%E4%B9%A6")) {
      title = decodeURI("%E5%B8%96%E5%90%8E")
    }
    contentArrX = currChapter.format;

    that.refuContentArrX();

    wx.setNavigationBarTitle({
      title: title + "  第" + currChapter.chapterId + "章",
      success: function(res) {
        backgroundAudioManager.stop();
        that.playBibleAudio.url = '';
      }
    });
    var lastread = currChapter.bookId + "-" + currChapter.chapterId + "-" + currChapter.bookName + "-" + currChapter.chapterCount + "-" + "1";
    var date = util.getNowShortFormatDate();
    var lastreadid = date + "-" + currChapter.bookId + "-" + currChapter.chapterId;
    wx.setStorageSync("lastread", lastread);
    glo.setLastRead(lastreadid);
    if (this.data.play && this.data.play == true) {
      let platform = that.data.platform;
      if (platform == 'android') {
        that.audioplay();
      } else {
        that.audioplay(1);
      }
      this.setData({
        play: false
      });
    }
    var lastRead10Obj = glo.getTopNRead(lastLen, currChapter.bookId, currChapter.chapterId);
    this.setData({
      lastRead10Obj: lastRead10Obj
    });

  },

  playSubtitles: function(bookid, chapterid) {
    var that = this;
    wx.request({
      url: glo.https + '/verse/chapter',
      data: {
        bookid: bookid,
        chapterid: chapterid,
      },
      success: function(res2) {
        that.setData({
          subtitles: res2.data
        });
      },
      fail: function(res2) {}
    })


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var platform = wx.getSystemInfoSync().platform;
    console.log(platform)
    wx.showLoading({
      title: "加载中",
      mask: true
    });
    console.log(options)
    oldbook = bibleData.oldbooks;
    newbook = bibleData.newbooks;
    var that = this;
    var favorite = "";
    this.setData({
      sign: sign_def,
      homeimage: 'home',
      punchimage: 'punch',
      platform: platform
    });
    wx.request({
      url: glo.https + '/person/getposter',
      success: function(res2) {
        var src0 = glo.https + '/static/posterImg/' + res2.data.src;
        console.log(src0)
        wx.getImageInfo({
          src: encodeURI(src0),
          success: function(sres) {
            that.setData({
              imgSrc: sres.path,
              posterIndex: res2.data.index
            });
          }
        });
      },
      fail: function(res2) {}
    })

    var pagetext = wx.getStorageSync('pagetext');
    if (pagetext != '') {
      that.setData({
        pagetext: pagetext
      });
    }

    var bgObj = wx.getStorageSync('bg');
    if (bgObj != '') {
      that.setData(bgObj);
      that.setData({
        setpagebgnum: bgObj.setpagebgnum
      });
      if (bgObj.setpagebgnum == 5) {
        that.setData({
          isNight: true
        });
      }
    }
    console.log(bgObj)

    var fontsize = wx.getStorageSync('fontsize');
    if (fontsize != '') {
      that.setData({
        fontsize: fontsize
      });
    }

    wx.getStorage({
      key: 'swichNext',
      success: function(res) {
        that.setData({
          swichNext: res.data
        });
      }
    });
    wx.getStorage({
      key: 'speed',
      success: function(res) {
        that.setData({
          speed: res.data
        });
      }
    });

    wx.getStorage({
      key: 'isOpenDaka',
      success: function(res) {
        that.setData({
          isOpenDaka: res.data
        });
        // that.setData({
        //   bottomDakaShow: that.data.isOpenDaKa
        // });

      },
      fail: function() {
        wx.setStorageSync('isOpenDaka', false);
        that.setData({
          bottomDakaShow: false
        });
      }
    })


    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo) {

      contentArrX = new Array();
      var bookName = options.bookName;
      var chapterId = options.chapterId;
      var bookId = options.bookId;
      var chapterCount = options.chapterCount;
      locationId = options.lid;
      pageFrom = options.from;
      that.data.bookName = bookName;
      that.data.bookId = bookId;
      that.data.chapterId = chapterId;
      that.data.chapterCount = chapterCount;
      var content = options.content;
      favorite = userInfo.favorite;
      console.log(pageFrom)

      //记录最近位置
      var lastread = bookId + "-" + chapterId + "-" + bookName + "-" + chapterCount + "-" + "1";
      var date = util.getNowShortFormatDate();
      var lastreadid = date + "-" + bookId + "-" + chapterId;
      wx.setStorageSync("lastread", lastread);
      glo.setLastRead(lastreadid);

    

      //更新数据
      that.setData({
        userInfo: userInfo,
        locationId: locationId
      });
      currChapter.bookId = bookId;
      currChapter.chapterId = chapterId;
      currChapter.chapterCount = chapterCount;
      currChapter.bookName = bookName;
      contentArrX = that.transContentArr(bookId, chapterId, content, favorite);
      currChapter.format = contentArrX;
      currChapter.content = content;
      rightChapter = glo.getRightChapter(bookId, chapterId, chapterCount);
      var contentArrRight = that.transContentArr(rightChapter.bookId, rightChapter.chapterId, rightChapter.content, favorite);
      rightChapter.format = contentArrRight;
      leftChapter = glo.getLeftChapter(bookId, chapterId, chapterCount);
      var contentArrLeft = that.transContentArr(leftChapter.bookId, leftChapter.chapterId, leftChapter.content, favorite);
      leftChapter.format = contentArrRight;

      if (bookName == "帖撒罗尼迦前书") {
        bookName = "帖前"
      }

      if (bookName == "帖撒罗尼迦后书") {
        bookName = "帖后"
      }
      var title = bookName + "  第" + chapterId + "章";

      var result = glo.punchCalc1(that.data.userInfo.punch);
      var todaycount = result.todaycount;
      that.setData({
        contentArr1: contentArrRight,
        contentArr0: contentArrX,
        contentArr2: contentArrLeft,
        todaycount: todaycount
      });

      wx.setNavigationBarTitle({
        title: title,
        success: function(res) {
          // success    
        }
      });
      wx.hideLoading();
    });
  },

  audioSrcChange: function() {
    var chapterId = currChapter.chapterId;
    var bookName = currChapter.bookName;
    var bookId = currChapter.bookId;
    var speedFile = '';
    var speed = parseInt(this.data.speed * 100);

    if (speed === 100) {
      speedFile = '100';
    } else if (speed < 100) {
      speedFile = '0' + speed;
    } else {
      speedFile = speed;
    }
    var src = glo.cdnurl + speedFile + "/" + bookId + "_" + chapterId + ".m"+"p3";
    console.debug(src);
    return encodeURI(src);
  },
  audioplay: function(e) {
    var chapterId = currChapter.chapterId;
    var bookName = currChapter.bookName;
    var bookId = currChapter.bookId;
    var that = this;

    var isDataset = 0;
    //是否选择播放
    if (e !== undefined) {
      if (typeof e === 'number') {
        isDataset = e;
      } else if (Object.keys(e.currentTarget.dataset).length !== 0 && e.currentTarget.dataset.ver != 0) {
        isDataset = parseInt(e.currentTarget.dataset.ver);
        that.setData({
          selVerseValue: isDataset
        });
      } else if (Object.keys(e.currentTarget.dataset).length !== 0 && e.currentTarget.dataset.ver == 0) {
        that.setData({
          selVerseValue: 0
        });
      }
    }


    var coverImgUrl = glo.https + "/static/100/webible.png";
    if (this.data.audioState && (e.type == 'tap')) { //如果播放就暂停
      backgroundAudioManager.pause();
      return;
    }
   
    var src = this.audioSrcChange();
    //this.plus();
    if (src == this.playBibleAudio.url && isDataset === 0) { //地址没变化就播放
      backgroundAudioManager.play();
      return;
    }
    if (src == this.playBibleAudio2.url && isDataset === 0) { //地址没变化就播放
      backgroundAudioManager.play();
      return;
    }
    console.log("isDataset" + isDataset);
    if (backgroundAudioManager.src == src &&backgroundAudioManager.buffered > 0 && backgroundAudioManager.paused && (e.type == 'tap') && isDataset == 0) { //如果暂停就开始播放
      backgroundAudioManager.play();
      console.log("继续播放000")
      return;
    }
    //平台    
    let platform = this.data.platform;

    if (platform == 'android') {
      if (isDataset !== 0) {
        that.playBibleAudio(bookName, "第" + chapterId + "章", "", coverImgUrl, src, bookId, chapterId, isDataset);
      } else {
        that.playBibleAudio(bookName, "第" + chapterId + "章", "", coverImgUrl, src, bookId, chapterId);
      }
    } else {
      if (isDataset !== 0) {
        that.playBibleAudio2(bookName, "第" + chapterId + "章", "", coverImgUrl, src, bookId, chapterId, isDataset);
      } else {
        that.playBibleAudio2(bookName, "第" + chapterId + "章", "", coverImgUrl, src, bookId, chapterId,1);
      }
    }
    //this.playBibleAudio.url = src;
  },

  playBibleAudio2: function(title, epname, singer, coverImagUrl, src, bookid, chapterid, isDataset) {
    wx.showLoading({
      title: '音频加载中···',
    });
    var that = this;
    var currPage = that.data.currPage;
    wx.request({
      url: glo.https + '/verse/chapter',
      data: {
        bookid: bookid,
        chapterid: chapterid,
      },
      success: function(res2) {
        setTimeout(function() {
          wx.hideLoading();
        }, 800);

        var subtitles = res2.data;
        backgroundAudioManager.title = title;
        backgroundAudioManager.epname = epname;
        backgroundAudioManager.singer = singer;
        backgroundAudioManager.coverImgUrl = coverImagUrl;
        backgroundAudioManager.src = src;

        console.log(isDataset)
        //选择
        if (isDataset !== undefined) {
          let sped = that.data.speed * 1;
          subtitles.forEach(function(item, index) {
            if (item.verseId === isDataset) {
              setTimeout(function() {
                that.tapcancel();
              }, 800);
              let stime = item.start / sped;
              backgroundAudioManager.startTime = stime;
            }
          });
        } else {
          console.log(pageFrom);
          let locationId = that.data.locationId * 1,
            sped = that.data.speed * 1;
          if (locationId !== 0) {
            subtitles.forEach(function(item, index) {
              if (item.verseId == locationId) {
                setTimeout(function() {
                  that.tapcancel();
                }, 800);
                let stime = item.start / sped;
                backgroundAudioManager.startTime = stime;
              }
            });
          } else {
            backgroundAudioManager.startTime = 0;
          }
        }
        backgroundAudioManager.onError(function(err) {
          console.log(err)
        });


        var y0 = 0;
        var verse0 = 0;

        var speed = that.data.speed;
        that.setData({
          homeimage: 'music',
          audioState: true
        });
        backgroundAudioManager.onTimeUpdate(function(callback) {
          var t = backgroundAudioManager.currentTime;
          for (var i = 0; i < subtitles.length; i++) {
            var start = parseInt(subtitles[i].start);
            var end = parseInt(subtitles[i].end);
            var verse = parseInt(subtitles[i].verseId);
            var lid = bookid + "-" + chapterid + "-" + subtitles[i].verseId;
            if (t > start / speed && t < end / speed && verse > verse0) {
              verse0 = verse;
              if (parseInt(that.data.fontsize) >= 52) {
                verse = verse;
              } else {
                verse = verse - 2;
              }
              var v0 = verse0 + "";
              var vid1 = "verse" + bookid + "-" + chapterid + "-" + verse;
              for (var k = 0; k < contentArrX.length; k++) {
                if (contentArrX[k][0] != "00000" && contentArrX[k][0] != "22222") {
                  for (var n = 0; n < contentArrX[k].length; n++) {
                    if (contentArrX[k][n][0] == v0) {
                      contentArrX[k][n][2] = "";
                      contentArrX[k][n][3] += " audioVerse";
                    } else {
                      contentArrX[k][n][2] = "";
                      contentArrX[k][n][3] = contentArrX[k][n][3].split(' ')[0];
                    }
                  }
                }
              }

              if (currPage == 0) {
                that.setData({
                  contentArr0: contentArrX
                });
                if (verse > 0) {
                  that.setData({
                    scrollTop0: vid1
                  });
                }
              } else if (currPage == 1) {
                that.setData({
                  contentArr1: contentArrX
                });
                if (verse > 0) {
                  that.setData({
                    scrollTop1: vid1
                  });
                }
              } else {
                that.setData({
                  contentArr2: contentArrX
                });
                if (verse > 0) {
                  that.setData({
                    scrollTop2: vid1
                  });
                }
              }
              var animationPlus = wx.createAnimation({
                duration: 5000,
                timingFunction: 'ease-out'
              })
              animationPlus.rotateZ(360 * verse).step();
              that.setData({
                animPlus: animationPlus.export()
              });
            }

          }
        });
        //自然结束事件，后面跳下一章

        backgroundAudioManager.onEnded(function(callback) {
          that.setData({
            audioState: false
          });
          that.refuContentArrX();
          that.setData({
            homeimage: 'home'
          });
          that.playBibleAudio2.url = '';

          if (!that.data.isOpenDaka) {
            var currTabNum = that.data.currTabNum;
            currTabNum++
            if (currTabNum == 3) {
              currTabNum = 0;
            }
            that.setData({
              currTabNum: currTabNum,
              play: true,
              dakaNext: true
            });
          } else if (that.data.isOpenDaka && that.data.punchimage !== 'read') {
            that.setData({
              bottomDakaShow: true
            });
            //确定后,自动播放下一章
            that.setData({
              play: true,
              dakaNext: true
            });
          } else if (that.data.isOpenDaka && that.data.punchimage === 'read') {
            wx.showToast({
              title: '已' + decodeURI('%E6%89%93%E5%8D%A1')+'的章节',
              duration: 2000
            });
          }
        });
        backgroundAudioManager.onStop(function(callback) {
          that.playBibleAudio2.url = "";
          that.setData({
            audioState: false
          });
          that.refuContentArrX();
          that.setData({
            homeimage: 'home'
          });
        });
        backgroundAudioManager.onPause(function() { //暂停
          that.setData({
            audioState: false,
          });
        });
        backgroundAudioManager.onPlay(function() { //开始
          that.setData({
            audioState: true,
          });
    
        });
      },
      fail: function(res2) {
        let v = that.data.selVerseValue;
        setTimeout(function() {
          that.audioplay(v);
        }, 3000);

      }
    })

  },

  playBibleAudio: function(title, epname, singer, coverImagUrl, src, bookid, chapterid, isDataset) {
    wx.showLoading({
      title: '音频加载中···',
    });
    var that = this;
    var currPage = that.data.currPage;
    var sTime = 0;
    wx.request({
      url: glo.https + '/verse/chapter',
      data: {
        bookid: bookid,
        chapterid: chapterid,
      },
      success: function(res2) {
        var subtitles = res2.data;
        console.log(src)
        backgroundAudioManager.title = title;
        backgroundAudioManager.epname = epname;
        backgroundAudioManager.singer = singer;
        backgroundAudioManager.coverImgUrl = coverImagUrl;
        backgroundAudioManager.src = src;

        setTimeout(function() {
          wx.showLoading({
            title: '音频加载中···',
          });
          backgroundAudioManager.pause();
        }, 500);


        backgroundAudioManager.onCanplay(function() {
          setTimeout(function() {
            let duration = backgroundAudioManager.duration,
              buffered = backgroundAudioManager.buffered;

            wx.hideLoading();
            backgroundAudioManager.play();
            //选择播放
            if (isDataset !== undefined) {
              let sped = that.data.speed * 1;
              subtitles.forEach(function(item, index) {
                if (item.verseId === isDataset) {
                  setTimeout(function() {
                    that.tapcancel();
                  }, 800);
                  let stime = item.start / sped;
                  if (buffered >= stime) {
                    backgroundAudioManager.seek(stime)
                  } else {
                    setTimeout(function() {
                      backgroundAudioManager.seek(stime)
                    }, 2000);
                  }
                }
              });
            } else {
              let locationId = that.data.locationId * 1,
                sped = that.data.speed * 1;
              if (locationId !== 0) {
                subtitles.forEach(function(item, index) {
                  if (item.verseId == locationId) {
                    setTimeout(function() {
                      that.tapcancel();
                    }, 800);
                    let stime = item.start / sped;
                    if (buffered >= stime) {
                      backgroundAudioManager.seek(stime)
                    } else {
                      setTimeout(function() {
                        backgroundAudioManager.seek(stime)
                      }, 2000);
                    }
                  }
                });
              }
            }
          }, 4000);

        });

        backgroundAudioManager.onError(function(err) {
          that.playBibleAudio.url = "";
          console.log(err)
          that.setData({
            audioState: false,
            homeimage: 'home'
          });
        });
        backgroundAudioManager.onWaiting(function(w) {
          console.log(11111111111)
          setTimeout(function() {
            backgroundAudioManager.pause();
            wx.showLoading({
              title: '加载音频中',
            })

          }, 500)

          setTimeout(function() {
            wx.hideLoading();
            backgroundAudioManager.play();
          }, 4000);
        });



        var y0 = 0;
        var verse0 = 0;

        var speed = that.data.speed;
        that.setData({
          homeimage: 'music',
          audioState: true
        });
        backgroundAudioManager.onTimeUpdate(function(callback) {
          var t = backgroundAudioManager.currentTime;
          for (var i = 0; i < subtitles.length; i++) {
            var start = parseInt(subtitles[i].start);
            var end = parseInt(subtitles[i].end);
            var verse = parseInt(subtitles[i].verseId);
            var lid = bookid + "-" + chapterid + "-" + subtitles[i].verseId;
            if (t > start / speed && t < end / speed && verse > verse0) {
              verse0 = verse;
              if (parseInt(that.data.fontsize) >= 52) {
                verse = verse;
              } else {
                verse = verse - 2;
              }
              // verse = verse - 3;
              var v0 = verse0 + "";
              var vid1 = "verse" + bookid + "-" + chapterid + "-" + verse;
              for (var k = 0; k < contentArrX.length; k++) {
                if (contentArrX[k][0] != "00000" && contentArrX[k][0] != "22222") {
                  for (var n = 0; n < contentArrX[k].length; n++) {
                    if (contentArrX[k][n][0] == v0) {
                      contentArrX[k][n][2] = "";
                      contentArrX[k][n][3] = "audioVerse";
                    } else {
                      contentArrX[k][n][2] = "";
                      contentArrX[k][n][3] = "";
                    }
                  }
                }

              }

              if (currPage == 0) {
                that.setData({
                  contentArr0: contentArrX
                });
                if (verse > 0) {
                  that.setData({
                    scrollTop0: vid1
                  });
                }
              } else if (currPage == 1) {
                that.setData({
                  contentArr1: contentArrX
                });
                if (verse > 0) {
                  that.setData({
                    scrollTop1: vid1
                  });
                }
              } else {
                that.setData({
                  contentArr2: contentArrX
                });
                if (verse > 0) {
                  that.setData({
                    scrollTop2: vid1
                  });
                }
              }
              var animationPlus = wx.createAnimation({
                duration: 5000,
                timingFunction: 'ease-out'
              })
              animationPlus.rotateZ(360 * verse).step();
              that.setData({
                animPlus: animationPlus.export()
              });
            }

          }
        });
        //自然结束事件，后面跳下一章
        backgroundAudioManager.onEnded(function(callback) {
          that.setData({
            audioState: false
          });
          that.refuContentArrX();
          that.setData({
            homeimage: 'home'
          });
          that.playBibleAudio.url = '';

          if (!that.data.isOpenDaka) {
            var currTabNum = that.data.currTabNum;
            currTabNum++
            if (currTabNum == 3) {
              currTabNum = 0;
            }
            that.setData({
              currTabNum: currTabNum,
              play: true,
              dakaNext: true
            });
          } else if (that.data.isOpenDaka && that.data.punchimage !== 'read') {
            that.setData({
              bottomDakaShow: true
            });
            //确定后,自动播放下一章
            that.setData({
              play: true,
              dakaNext: true
            });
          } else if (that.data.isOpenDaka && that.data.punchimage === 'read') {
            wx.showToast({
              title: '已' + decodeURI('%E6%89%93%E5%8D%A1')+'的章节',
              duration: 2000
            });
          }
        });
        backgroundAudioManager.onStop(function(callback) {
          console.log("停了停了:" + backgroundAudioManager.currentTime);
          that.playBibleAudio.url = "";
          that.setData({
            audioState: false
          });
          that.refuContentArrX();
          that.setData({
            homeimage: 'home'
          });
        });
        backgroundAudioManager.onPause(function() { //暂停
          that.setData({
            audioState: false,
          });
        });
        backgroundAudioManager.onPlay(function() { //开始
          that.setData({
            audioState: true,
          });
    
        
        });
      },
      fail: function(res2) {
        let v = that.data.selVerseValue;
        setTimeout(function() {
          that.audioplay(v);
        }, 5000);

      }
    })

  },

  tap_mark: function(e) {
    var that = this;
    var currPage = that.data.currPage;
    if (that.data.audioState) {
      return;
    }
    var markVerse = [];
    var markIndex = 0;

    var bookId = currChapter.bookId;
    var chapterId = currChapter.chapterId;
    var favorite = that.data.userInfo.favorite || '';
    var ismark = that.data.ismark;
    var edit_fav = "";
    for (var k = 0; k < contentArrX.length; k++) {
      if (contentArrX[k][0] != "00000" && contentArrX[k][0] != "22222") {
        for (var n = 0; n < contentArrX[k].length; n++) {
          if (contentArrX[k][n][2] == "selVerse") {
            contentArrX[k][n][2] = "";
            contentArrX[k][n][5] = "";
            if (!that.data.isNight) {
              contentArrX[k][n][3] = "markVerse";
            } else {
              contentArrX[k][n][3] = "markVerse1";
            }
            var vid = ";#" + bookId + "-" + chapterId + "-" + contentArrX[k][n][0] + "#";
            var sindex = favorite.indexOf(vid);
            if (sindex == -1) {
              favorite = favorite + vid;
              edit_fav = edit_fav + vid;
            } else {
              if (ismark == del_image) {
                if (favorite.indexOf(vid) > -1) {
                  favorite = favorite.replace(vid, "");
                  contentArrX[k][n][3] = "";
                  edit_fav = edit_fav + vid;
                }
              }

            }

          }
        }
      }
    }

    var isAdd = 'add';
    if (ismark == del_image) {
      isAdd = 'del';
    }

    // longtab = false;
    //发起网络请求注册
    wx.request({
      url: glo.https + '/person/fav_update1',
      data: {
        edit_fav: edit_fav,
        addordel: isAdd,
        userid: that.data.userInfo.userId
      },
      success: function(res2) {
        that.data.userInfo.favorite = favorite;
        app.setUserInfo(that.data.userInfo);
        if (currPage == 0) {
          that.setData({
            contentArr0: contentArrX,
            bottom_menu: "bottom_menu_none"
          });
        } else if (currPage == 1) {
          that.setData({
            contentArr1: contentArrX,
            bottom_menu: "bottom_menu_none"
          });
        } else {
          that.setData({
            contentArr2: contentArrX,
            bottom_menu: "bottom_menu_none"
          });
        }
        that.showBottomMenu('bottom_menu_none');

      }
    })

  },

  getSelVers: function(selContents, selIndexs, selChapters) {
    var verContentArr = [];
    var verIndexArr = [];
    var index = 0;
    for (var k = 0; k < contentArrX.length; k++) {
      if (contentArrX[k][0] != "00000" && contentArrX[k][0] != "22222") {
        for (var n = 0; n < contentArrX[k].length; n++) {
          if (contentArrX[k][n][2] == "selVerse") {
            // copydata = copydata + contentArrX[k][n][0] + contentArrX[k][n][1];
            contentArrX[k][n][2] = "";
            contentArrX[k][n][5] = "";
            verContentArr[index] = contentArrX[k][n][1];
            verIndexArr[index] = contentArrX[k][n][0];
            index = index + 1;
          }
        }
      }
    }
    var minx = -1;
    var maxx = -1;
    var maxmin = new Array();
    var nn = 0;
    for (var i = 0; i < index; i++) {
      if (minx == -1) {
        minx = verIndexArr[i];
        maxx = verIndexArr[i];
      }
      if (i + 1 < index) {
        if (verIndexArr[i + 1] - verIndexArr[i] == 1) {
          maxx = verIndexArr[i + 1];
        } else {
          maxmin[nn] = new Array();
          maxmin[nn][0] = minx;
          maxmin[nn][1] = maxx;
          nn = nn + 1;
          minx = -1;
          maxx = -1;
        }
      } else {
        maxmin[nn] = new Array();
        maxmin[nn][0] = minx;
        maxmin[nn][1] = maxx;
      }
    }
    var bname = currChapter.bookName;
    var bid = currChapter.bookId;
    var cid = currChapter.chapterId;
    var kn = 0;
    var selN = 0;
    for (var k = 0; k <= nn; k++) {
      var ma = maxmin[k][0];
      var mb = maxmin[k][1];
      if (ma == mb) {
        selChapters[selN] = bid + "|" + cid + ":" + ma;
        selContents[selN] = verContentArr[kn];
        selIndexs[selN] = bname + cid + ":" + ma;
        selN = selN + 1
        kn = kn + 1;
      } else {
        var ln = mb - ma + 1;
        var cnten = "";
        for (var kd = 0; kd < ln; kd++) {
          cnten = cnten + verContentArr[kn + kd];
        }
        kn = kn + ln;
        selChapters[selN] = selChapters[selN] = bid + "|" + cid + ":" + ma + "-" + mb;
        selContents[selN] = cnten;
        selIndexs[selN] = bname + cid + ":" + ma + "-" + mb;
        selN = selN + 1;
      }
    }
  },

  tap_notbe: function(e) {
    var that = this;
    var selContents = new Array();
    var selIndexs = new Array();
    var selChapters = new Array();
    this.getSelVers(selContents, selIndexs, selChapters);
    var currPage = that.data.currPage;
    if (currPage == 0) {
      that.setData({
        contentArr0: contentArrX,
        bottom_menu: "bottom_menu_none"
      });
    } else if (currPage == 1) {
      that.setData({
        contentArr1: contentArrX,
        bottom_menu: "bottom_menu_none"
      });
    } else {
      that.setData({
        contentArr2: contentArrX,
        bottom_menu: "bottom_menu_none"
      });
    }
    that.showBottomMenu('bottom_menu_none');
    wx.navigateTo({
      url: '../editnotbe/editnotbe?content=' + JSON.stringify(selContents) + '&index=' + JSON.stringify(selIndexs) + '&chapter=' + JSON.stringify(selChapters) + "&edit=0",
    })
  },
  changeScreenLight: function(e) {
    wx.setScreenBrightness({
      value: parseFloat(e.detail.value).toFixed(1)
    })
  },
  tap_copy: function(e) {
    var that = this;
    var copydata = "";
    var selContents = new Array();
    var selIndexs = new Array();
    var selChapters = new Array();
    var currPage = that.data.currPage;
    this.getSelVers(selContents, selIndexs, selChapters);
    for (var i = 0; i < selContents.length; i++) {
      copydata = copydata + selContents[i] + "(" + selIndexs[i] + ")";
    }
    // longtab = false;
    if (currPage == 0) {
      this.setData({
        contentArr0: contentArrX,
        bottom_menu: "bottom_menu_none",
        status: false
      });
    } else if (currPage == 1) {
      this.setData({
        contentArr1: contentArrX,
        bottom_menu: "bottom_menu_none",
        status: false
      });
    } else {
      this.setData({
        contentArr2: contentArrX,
        bottom_menu: "bottom_menu_none",
        status: false
      });
    }
    that.showBottomMenu('bottom_menu_none');
    wx.setClipboardData({
      data: copydata,
      success: function(res) {
        wx.getClipboardData({
          success: function(res) {
            for (var k = 0; k < contentArrX.length; k++) {
              if (contentArrX[k][0] != "00000" && contentArrX[k][0] != "22222") {
                for (var n = 0; n < contentArrX[k].length; n++) {
                  if (contentArrX[k][n][2] == "selVerse") {
                    contentArrX[k][n][2] = "";
                  }
                }
              }
            }


          }
        })
      }
    });
    that.tapcancel();
  },
  toastHide: function(event) {
    console.log("触发bindchange，隐藏toast")
    this.setData({
      status: true
    })
  },

  tapver: function(e) { //点击
    var top = e.detail.y;
    var that = this;
    var currPage = that.data.currPage;
    if (that.data.audioState) {
      return;
    }
    //  if (e.type == "tap" && longtab == true) {
    if (e.type == "tap") {
      var i = parseInt(e.target.dataset.i);
      var j = parseInt(e.target.dataset.j);
      if (contentArrX[i][0] == "00000" || contentArrX[i][0] == "22222") {
        return;
      }
      if (contentArrX[i][j][2] == "") {
        contentArrX[i][j][2] = "selVerse";
        contentArrX[i][j][5] = selVerseClass;

        // if (that.data.tapVerse === 0) {
        //   that.setData({
        //     tapVerse: parseInt(e.currentTarget.dataset.ver)
        //   });
        // }

      } else {
        contentArrX[i][j][2] = "";
        contentArrX[i][j][5] = "";
        var longtab = false;
        for (var k = 0; k < contentArrX.length; k++) {
          if (contentArrX[k][0] != "00000" && contentArrX[k][0] != "22222") {
            for (var n = 0; n < contentArrX[k].length; n++) {
              if (contentArrX[k][n][2] == "selVerse") {
                longtab = true;
              }
            }
          }
        }

      }

      var bottom_menu_class = "bottom_menu";
      if (longtab == false) {
        bottom_menu_class = "bottom_menu_none";
      }
      var verseid0 = 1;
      var selVerArr = [];
      //判断所有选中的是否都标记过
      var bookId = currChapter.bookId;
      var chapterId = currChapter.chapterId;
      var favorite = this.data.userInfo.favorite || '';
      var ismark = del_image;
      var cancle_class = cancleClass;
      for (var k = 0; k < contentArrX.length; k++) {
        if (contentArrX[k][0] != "00000" && contentArrX[k][0] != "22222") {
          for (var n = 0; n < contentArrX[k].length; n++) {
            if (contentArrX[k][n][2] == "selVerse") {
              var vid = ";#" + bookId + "-" + chapterId + "-" + contentArrX[k][n][0] + "#";
              verseid0 = contentArrX[k][n][0];
              selVerArr.push(contentArrX[k][n][0]);
              if (favorite.indexOf(vid) == -1) {
                ismark = line_image;
                cancle_class = "";
              }
            }
          }
        }
      }
      //选中的节数
      that.setData({
        tapVerse: parseInt(verseid0),
        selVerArr: selVerArr
      });
      if (currPage == 0) {
        that.setData({
          contentArr0: contentArrX,
          ismark: ismark,
          cancle_class: cancle_class,
          bottom_menu: bottom_menu_class
        });
      } else if (currPage == 1) {
        that.setData({
          contentArr1: contentArrX,
          ismark: ismark,
          cancle_class: cancle_class,
          bottom_menu: bottom_menu_class
        });
      } else {
        that.setData({
          contentArr2: contentArrX,
          ismark: ismark,
          cancle_class: cancle_class,
          bottom_menu: bottom_menu_class
        });
      }
      that.showBottomMenu(bottom_menu_class);
    }
  },

  showBottomMenu: function(bottom_menu, top) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 500
    });
    if (bottom_menu == 'bottom_menu') {
      animation.translateY(0).step();
    } else {
      animation.translateY(-100).step();
    }
    that.setData({
      animationData: animation.export()
    });
  },

  tapcancel: function(e) {
    var that = this;
    var currPage = that.data.currPage;
    for (var k = 0; k < contentArrX.length; k++) {
      if (contentArrX[k][0] != "00000" && contentArrX[k][0] != "22222") {
        for (var n = 0; n < contentArrX[k].length; n++) {
          contentArrX[k][n][2] = "";
          contentArrX[k][n][5] = "";
        }
      }
    }
    // longtab = false;
    if (currPage == 0) {
      this.setData({
        contentArr0: contentArrX,
        bottom_menu: "bottom_menu_none"
      });
    } else if (currPage == 1) {
      this.setData({
        contentArr1: contentArrX,
        bottom_menu: "bottom_menu_none"
      });
    } else {
      this.setData({
        contentArr2: contentArrX,
        bottom_menu: "bottom_menu_none"
      });
    }
    that.showBottomMenu('bottom_menu_none');
    //重置选择的节    
    //that.setData({ tapVerse: 0 });
    that.setData({
      locationId: 0,
    });
  },
  longtapver: function(e) {
    // longtab = true;
    // this.setData({ bottom_menu: "bottom_menu" });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    if (!wx.canIUse('createSelectorQuery')) {
      return;
    }
    setTimeout(function() {
      that.setData({
        bottomDakaShow: true
      })
    }, 2000)

    //console.debug("定位标识" + locationId);

    var currPage = that.data.currPage;
    if (locationId != undefined) {
      if (locationId != -1) {
        var ismark = line_image;
        var bookId = currChapter.bookId;
        var chapterId = currChapter.chapterId;
        var favorite = that.data.userInfo.favorite;
        if (locationId > 3) {
          var verse_index = locationId - 3;
          var locationY = "verse" + bookId + "-" + chapterId + "-" + verse_index;
          if (currPage == 0) {
            that.setData({
              scrollTop0: locationY
            });
          } else if (currPage == 1) {
            that.setData({
              scrollTop1: locationY
            });
          } else {
            that.setData({
              scrollTop2: locationY
            });
          }

        }
        if (pageFrom != undefined && pageFrom != -1) {
          if (pageFrom == 0) { //来自查询入口
            for (var k = 0; k < contentArrX.length; k++) {
              if (contentArrX[k][0] != "00000" && contentArrX[k][0] != "22222") {
                for (var n = 0; n < contentArrX[k].length; n++) {
                  if (contentArrX[k][n][0] == locationId) {
                    contentArrX[k][n][2] = "selVerse";
                    contentArrX[k][n][5] = selVerseClass;
                    var vid = ";#" + bookId + "-" + chapterId + "-" + contentArrX[k][n][0] + "#";
                    if (favorite.indexOf(vid) != -1) {
                      ismark = del_image;

                    }
                    //longtab = true;
                  }
                }
              }
            }
            if (currPage == 0) {
              this.setData({
                contentArr0: contentArrX,
                bottom_menu: "bottom_menu",
                ismark: ismark
              });
            } else if (currPage == 1) {
              this.setData({
                contentArr1: contentArrX,
                bottom_menu: "bottom_menu",
                ismark: ismark
              });
            } else {
              this.setData({
                contentArr2: contentArrX,
                bottom_menu: "bottom_menu",
                ismark: ismark
              });
            }
            that.showBottomMenu('bottom_menu');

          }
        }
        locationId = -1;
        pageFrom = -1;
      }
    }
    // this.setChapter(currChapter.bookId, currChapter.chapterId)

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var bookId=this.data.bookId;
    var chapterId=this.data.chapterId;
    var lastRead10Obj = glo.getTopNRead(lastLen,bookId,chapterId);
    this.setData({
      lastRead10Obj: lastRead10Obj
    });
    this.onPunch();


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    var j = 1;
    j = j + 1;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this;
    backgroundAudioManager.stop();


  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    console.log('有下拉操作');
  },

  /**
   * 判断
   */
  onPunch: function() {

    var that = this;
    var punch = that.data.userInfo.punch;
    var bookId = currChapter.bookId;
    var chapterId = currChapter.chapterId;
    var date = util.getNowShortFormatDate();
    var punch0 = "#" + date + "-" + bookId + "-" + chapterId + "#";
    that.setData({
      punchimage: 'punch'
    });

    if (punch && punch.indexOf(punch0) > -1) {
      that.setData({
        punchimage: 'read'
      });
      return;
    }
    var result = glo.punchCalc1(punch);
    var todaycount = result.todaycount;
    if (todaycount >= 100) { //最多允许100次
      that.setData({
        punchimage: 'read'
      });
      return;
    }
    if (!that.data.hasSign) {
      that.setData({
        punchimage: 'punch'
      });
    }

  },

  tap_sign: function(e) {
    //开启模式
    var that = this;
    var isOpenDaka = that.data.isOpenDaka;


    if (isOpenDaka) {
      
      wx.showModal({
        title: decodeURI("%E8%AF%BB%E7%BB%8F%E6%89%93%E5%8D%A1")+ '提示',
        content: '确定关闭' + decodeURI('%E6%89%93%E5%8D%A1')+'模式？',
        success: function(res) {
          if (res.confirm) {
            //网络请求						
            that.setData({
              isOpenDaka: false,
              bottomDakaShow: false
            });
            wx.setStorageSync('isOpenDaka', false);
          } else {

          }
        }
      });
    } else {
      wx.showModal({
        title: decodeURI("%E8%AF%BB%E7%BB%8F%E6%89%93%E5%8D%A1")+'提示',
        content: decodeURI('%E6%89%93%E5%8D%A1')+'有助于养成好习惯，每天前进一小步，日积月累带来新高度',
        success: function(res) {
          if (res.confirm) {
            that.setData({
              isOpenDaka: true
            });
            wx.setStorageSync('isOpenDaka', true);
          } else {

          }
        }
      });

    }

   
  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function(res) {
    var url = `/pages/content/content?bookName=${currChapter.bookName}&chapterId=${currChapter.chapterId}&chapterCount=${currChapter.chapterCount}&bookId=${currChapter.bookId}&content=${currChapter.content}&lid=1&from=3`;
    var v = "菜单";
    if (this.data.pageEnable) {
      v = "%E5%9C%A3%E7%BB%8F"
      v = decodeURI(v)
    }
    return {
      title: ' 这是一款免下载的小程序' + v + ',点开即可马上使用！',
      desc: '微信小程序版本' + v,
      path: url
    }
  },
  onPageScroll: function(e) {},
  hideTool: function(e) { //滑动隐藏工具栏
    var bool = this.data.scrollTool;
    var that = this;
    // if (that.data.bottomDakaShow == true) {
    //   return;
    // }
    if (bool === true) {
      return;
    }
    that.setData({
      scrollTool: true
    })
  },
  showTool: function(e) {
    var bool = this.data.scrollTool;
    var that = this;
    if (bool === false) {
      return;
    }
    setTimeout(function() {
      that.setData({
        scrollTool: false
      })
    }, 700);

  },
  creartImg: function() {
    // 使用 wx.createContext 获取绘图上下文 context
    var that = this;
    var text = that.data.text;
    var tit = that.data.tit;
    var n = Math.ceil(text.length / 19);
    var n0 = 0;
    var cardHx = 962;
    //var n1=n;
    if (n > 5) {
      n0 = n - 5;
      cardHx = 962 + n0 * 42;
      //  that.setData({cardH:cardHx});
      //   n1 = 5
    }
    var ctx = wx.createCanvasContext('firstCanvas');

    wx.getImageInfo({
      src: that.data.imgSrc,
      success: function(res) {
        var h = res.height / (res.width / 602);
        ctx.drawImage(that.data.imgSrc, 0, 0, 602, h);
        ctx.save();
        h = cardHx - n * 42 - 45 - 196;
        ctx.drawImage(that.data.lineSrc, 0, h - 82, 602, 82);
        ctx.save();

        // ctx.beginPath();
        // ctx.moveTo(0, h);
        // ctx.lineTo(602, h - 82);
        // ctx.lineTo(602, h);
        // ctx.closePath();
        // ctx.fillStyle = "#0000ff";
        // ctx.fill();
        ctx.setFillStyle('#ffffff');
        ctx.fillRect(0, h, 602, cardHx - h);
        ctx.setFillStyle('#444444'); // 文字颜色：黑色
        ctx.setTextAlign('left'); // 文字居中
        ctx.setFontSize(26); // 文字字号：22px
        // text = text.substr(0, 93);
        // if (text.length == 93) {
        //   text = text + '…';
        // }
        for (var i = 0; i < n; i++) {
          var str = text.substr(i * 19, 19);
          ctx.fillText(str, 52, h + 65 + i * 42);
        }
        // ctx.stroke();
        var yy = h + 45 + n * 42 + 40;
        ctx.drawImage('../../images/code.jpg', 440, yy, 116, 116);
        ctx.rect(52, yy + 26, 62, 6);
        ctx.setFillStyle('#404040');
        ctx.fill();

        ctx.setTextAlign('left'); // 文字居中
        ctx.setFillStyle('#444444'); // 文字颜色：黑色
        ctx.setFontSize(26); // 文字字号：22px
        ctx.fillText(tit, 52, yy + 75);
        console.debug("cardHx:" + cardHx);
        // ctx.stroke();
        ctx.draw(false, function() {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 602,
            height: cardHx,
            canvasId: 'firstCanvas',
            success: function(res) {
              console.log(res.tempFilePath);
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function(res11) {
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                  that.setData({
                    cardvisible: 'none'
                  });
                }
              });
            }
          })
        });
      }
    });
  },
  closeImage: function() {
    this.setData({
      cardvisible: 'none'
    });
  },
  chooseImage: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: glo.https + '/person/getnextposter',
      data: {
        index: that.data.posterIndex
      },
      success: function(res2) {
        var src0 = glo.https + '/static/posterImg/' + res2.data.src;
        wx.getImageInfo({
          src: encodeURI(src0),
          success: function(sres) {
            that.setData({
              imgSrc: sres.path,
              posterIndex: res2.data.index
            });
            wx.hideLoading();
          },
          fail: function(res3) {
            console.log(res3);
            wx.hideLoading();
          }
        });
      },
      fail: function(res2) {
        wx.hideLoading();
      }
    })
  },
  myCatchTouch: function(e) {
    //阻止滚动穿透
    return;
  },
  scroll: function(e) {

  },
  goChaper:function(e){
    var bookId = e.target.dataset.bookid;
    var chapterId = e.target.dataset.chapterid;
    var bookName = e.target.dataset.bookname;
    var that=this;

    var options={};

    options.bookId=bookId;
    options.bookName=bookName;
    options.chapterId=chapterId;
    
    var content = "";
    var keyid = "CH" + "-" + bookId + "-" + chapterId;

    wx.getStorage({
      key: "bk" + bookId,
      success: function (res) {
        var chapterCount = res.data.length;
        wx.showLoading({
          title: "正在加载...",
          mask: true
        });
        var bookData = res.data;
        for (var i = 0; i < bookData.length; i++) {
          if (chapterId == bookData[i].chapterId) {
            content = bookData[i].content;
            console.log("缓存读取" + bookName + "第" + chapterId + "章");
            options.chapterCount = chapterCount;
            options.content=content;
            
            var lastRead10Obj = glo.getTopNRead(lastLen, bookId, chapterId);
            that.setData({
              lastRead10Obj: lastRead10Obj
            });
            that.onLoad(options);
            // wx.navigateTo({
            //   url: '../content/content' + '?bookName=' + bookName + '&chapterId=' + chapterId + '&chapterCount=' + chapterCount + '&bookId=' + bookId + '&content=' + content,
            //   success: function (res) {
            //     wx.hideLoading();
            //     // success
            //   },
            //   fail: function () {
            //     wx.hideLoading();
            //     // fail
            //   }
            // })
          }
        }
      },
      fail: function () {
        wx.showLoading({
          title: "首次加载该卷",
          mask: true
        });
        wx.request({
          url: glo.https + '/chapter/list_bookid?bookId=' + bookId,
          method: 'GET',
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            wx.setStorage({ //添加缓存
              key: "bk" + bookId,
              data: res.data
            });
            var bookData = res.data;
            for (var i = 0; i < bookData.length; i++) {
              if (chapterId == bookData[i].chapterId) {
                content = bookData[i].content;
                console.log("缓存读取" + bookName + "第" + chapterId + "章");
                options.chapterCount = chapterCount;
                options.content = content;
                var lastRead10Obj = glo.getTopNRead(lastLen, bookId, chapterId);
                that.setData({
                  lastRead10Obj: lastRead10Obj
                });
                that.onLoad(options);
                // wx.navigateTo({
                //   url: '../content/content' + '?bookName=' + bookName + '&chapterId=' + chapterId + '&chapterCount=' + chapterCount + '&bookId=' + bookId + '&content=' + content ,
                //   success: function (res) {
                //     wx.hideLoading();
                //     // success
                //   },
                //   fail: function () {
                //     wx.hideLoading();
                //     wx.showToast({
                //       title: '加载失败，请检查网络',
                //       icon: 'loading',
                //       duration: 1000
                //     })
                //     // fail
                //   }
                // })
              }
            }
          }
        })
      }
    });
  }
})